/**   
* @Title: EntrylistService.java 
* @Package com.csis.system.service 
* @Description: TODO
* @author dailey  
* @date 2012-10-8
* @version V1.0   
*/
package com.csis.system.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.csis.framework.db.BaseDao;
import com.csis.framework.domain.Condition;
import com.csis.system.common.IStaticData;
import com.csis.system.common.WebUtil;
import com.csis.system.domain.Entrylist;
import com.csis.system.domain.EntrylistFormBean;

/**
 * @author dailey
 *
 */
@Service
public class EntrylistService {
	@Autowired
	private BaseDao baseDao;

	public Entrylist load(String no) {
		Entrylist bean = baseDao.load(Entrylist.class, no);
		return bean;
	}

	public EntrylistFormBean list(EntrylistFormBean formBean) {
		Integer currUserId = formBean.getUserId();
		if (currUserId == null) {
			return formBean;
		}
		String sql = getSearchSql(formBean);

		Condition condition = formBean.getCondition();
		if (condition != null) {
			sql = condition.getCondition(sql);
		}
		// importance
		int maxCount = getMaxCount(formBean);
		formBean.getPage().setMaxCount(maxCount);
		sql = formBean.getPage().perPageSql(sql);
		List<Entrylist> beans = baseDao.query4SingleTable(Entrylist.class, sql);
		formBean.setBeans(beans);
		return formBean;
	}

	/**
	 * @param formBean
	 * @return
	 */
	public String getSearchSql(EntrylistFormBean formBean) {
		Integer currUserId = formBean.getUserId();
		String sql = "SELECT * FROM " + IStaticData.TABLE_ENTRYLIST + " WHERE 1=1 ";
		if (currUserId != null && !WebUtil.isShowAll(formBean)) {
			sql += " AND " + IStaticData.COLUMN_ENTRYLIST_USERID + " = " + currUserId + " ";
		}
		return sql;
	}

	/**
	 * @return
	 */
	public int getMaxCount(EntrylistFormBean formBean) {
		return baseDao.getMaxCount(getSearchSql(formBean));
	}

	@Transactional
	public void save(Entrylist bean) {
		if (bean.getId() == null) {
			bean.setId(WebUtil.generateNo());
			baseDao.persist(bean);
		} else {
			baseDao.merge(bean);
		}
	}
}
